﻿using Azure;
using DataModels.Dto;
using DataModels.Dto.Home;
using DataModels.Dto.House;
using DataModels.Dto.WorkOrder;
using DataModels.Entities.AuthCore;
using DataModels.Entities.Base;
using DataModels.Entities.House;
using DataModels.Entities.ParkingLot;
using DataModels.Entities.WorkOrder;
using Dm.util;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using SEGIService.Service.Basic.House;
using SEGIService.SGModel;
using Services.AuthCore;
using SqlSugar;
using System.Threading.Tasks;
using Utils;
using WeChatServices;

namespace Services.House
{
    public class ArrearsInquiryService(SqlSugarClient db, SEGIHouseService sEGIHouseService, OauthService _oauthService, IConfiguration configuration) : BaseService(db)
    {
        protected readonly SEGIHouseService _sEGIHouseService = sEGIHouseService;
        private readonly WeChatMessageHandler _messageHandler = new WeChatMessageHandler(configuration, _oauthService);

        public async Task<ResponseModel> NotificationArrearsUsers()
        {
            string billingCycleStart = DateTime.Now.AddYears(-5).ToString("yyyyMM");
            string billingCycleEnd = DateTime.Now.ToString("yyyyMM");
            string appType = "fwh";
            var accessToken = await _oauthService.GetAccessToken(appType);
            if (accessToken == null)
                return null;
            string templateId = _messageHandler.GetTemplateMessageID("物业欠费通知");
            int total = 0;
            var mpopen_idAndHouseId = db.Queryable<Customer>()
                .Where(c => c.mpopen_id != null && c.mpopen_id != "")
                .InnerJoin<CustomerHouseRelation>((c, ch) => c.CustId == ch.CustId)
                .Select((c, ch) => new Mpopen_idAndHouseIdDto { mpopen_id = c.mpopen_id, HouseId = ch.HouseId })
                .ToList();

            // 要根据 HousingBasic  OrganId分组 项目ID分组
            List<Projectsqianfei> lProjectsqianfeis = db.Queryable<Projects>()
                .Where(n => n.OrganStatus == "1")
                .Select(n => new Projectsqianfei() { CommunityId = Convert.ToInt32(n.CommunityId),ProjectName=n.ProjectName })
                .ToList();
            // 查询所有房屋 houseIds  一次最多10个
            List<int> organIds= lProjectsqianfeis.Select(n=>n.CommunityId).ToList();
            foreach (var organId in organIds)
            {
                List<int> houseIds = db.Queryable<HousingBasic>()
                            .Where(h => h.HouseId != 0 && h.HouseId > 800 && h.OrganId == organId).Select(n => n.HouseId).ToPageList(1, 10, ref total);

                
                for (int thisindexpage = 2; houseIds.Count > 0; thisindexpage++)
                {
                    // 请求四格 获取欠费
                    var bodyObject = new
                    {
                        communityId = organId, //项目ID（真实小区ID）
                        houseIds = houseIds,
                        billingCycleStart,
                        billingCycleEnd
                    };
                    List<sigeArrearshouse10sum2> arrearsDataModels = await _sEGIHouseService.sigearrears(bodyObject);
                    await Task.Delay(800); // 防止过快请求
                    //模板通知客户
                    //发送模板消息
                    foreach (sigeArrearshouse10sum2 item in arrearsDataModels)
                    {
                        try
                        {

                            Mpopen_idAndHouseIdDto m1 = mpopen_idAndHouseId.Where(m => m.HouseId == item.houseId).FirstOrDefault();
                            if (m1 != null)
                            {
                                string openId = m1.mpopen_id; // "用户的openId 服务号";
                                if (string.IsNullOrWhiteSpace(openId))
                                    continue;
                                // 构造模板消息数据，根据模板要求设置
                                var fieldValues = new Dictionary<string, string>
                                {
                                    {"thing16", lProjectsqianfeis.Where(n=>n.CommunityId==organId).FirstOrDefault().ProjectName}, // 小区
                                    {"thing7", item.houseName}, // 修复为空的字段
                                    {"thing6", item.custBills[0].custName} // 业主姓名
                                };
                                string pagePath = "/packageA/payment/propertyFee"; //点击模板跳转页面
                                string dataJson = _messageHandler.BuildTemplateMessageWithMultipleKeywords(openId, templateId, pagePath, fieldValues);

                                var result = _messageHandler.SendTemplateMessage(accessToken, openId, templateId, dataJson);
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                    houseIds = db.Queryable<HousingBasic>()
                               .Where(h => h.HouseId != null && h.HouseId > 800 && h.OrganId == organId).Select(n => n.HouseId).ToPageList(thisindexpage, 10, ref total);

                    Console.WriteLine("四格欠费查询 房间数"+ houseIds.Count);
                }
            }
            return Success();
        }

    }
}
